package com.android.luhnchecking.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.android.luhnchecking.LuhnNumber;

public class AccountDao {
	protected Database mDatabase;

	public AccountDao(Context context) {
		mDatabase = Database.getInstance(context);
	}

	public long insert(LuhnNumber number) {
		SQLiteDatabase database = mDatabase.getWritable();

		ContentValues values = new ContentValues();
		values.put(DbHelper.COLUMN_ACCOUNT_NUMBER, number.getValue());
		values.put(DbHelper.COLUMN_STATUS, number.isPassed() ? 1 : 0);
		values.put(DbHelper.COLUMN_TIME, number.getTimeStamp());

		return database.insert(DbHelper.TABLE_ACCOUNT, null, values);
	}

	public LuhnNumber get(final String field, final String value) {
		final String query = String.format("select * from %s where %s=%s;",
				DbHelper.TABLE_ACCOUNT, field, value);
		LuhnNumber number = null;

		Cursor cursor = mDatabase.getReadable().rawQuery(query, null);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			long id = cursor.getLong(cursor.getColumnIndex(DbHelper.COLUMN_ID));
			String account = cursor.getString(cursor
					.getColumnIndex(DbHelper.COLUMN_ACCOUNT_NUMBER));
			boolean isPassed = cursor.getInt(cursor
					.getColumnIndex(DbHelper.COLUMN_STATUS)) == 1 ? true
					: false;
			long time = cursor.getLong(cursor
					.getColumnIndex(DbHelper.COLUMN_TIME));

			number = new LuhnNumber();
			number.setId(id);
			number.setPassed(isPassed);
			number.setValue(account);
			number.setTimeStamp(time);
		}
		cursor.close();

		return number;
	}

	public List<LuhnNumber> getAll() {
		ArrayList<LuhnNumber> list = new ArrayList<LuhnNumber>();
		final String query = String.format(
				"select * from %s order by %s desc;", DbHelper.TABLE_ACCOUNT,
				DbHelper.COLUMN_TIME);

		Cursor cursor = mDatabase.getReadable().rawQuery(query, null);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			do {
				long id = cursor.getLong(cursor
						.getColumnIndex(DbHelper.COLUMN_ID));
				String account = cursor.getString(cursor
						.getColumnIndex(DbHelper.COLUMN_ACCOUNT_NUMBER));
				boolean isPassed = cursor.getInt(cursor
						.getColumnIndex(DbHelper.COLUMN_STATUS)) == 1 ? true
						: false;
				long time = cursor.getLong(cursor
						.getColumnIndex(DbHelper.COLUMN_TIME));

				LuhnNumber number = new LuhnNumber();
				number.setId(id);
				number.setPassed(isPassed);
				number.setValue(account);
				number.setTimeStamp(time);
				list.add(number);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return list;
	}
}
